import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { request } from '@/api/request';

// AI角色数据类型定义
export interface AiPersonData {
  id: number;
  image: string;
  avatar: string;
  username: string;
  isPremium: boolean;
  description: string;
  images: string[];
  videos: string[];
  age: number;
  gender: string;
  zodiac: string;
  birthday: string;
  jobs: string[];
  language?: string;
  occupation?: string;
  information?: {
    age?: number;
    name?: string;
    gender?: string;
    zodiac?: string;
    birthday?: string;
    language?: string;
    occupation?: string;
  };
  status?: boolean; // 新增：在线状态
}

// localStorage中存储的数据类型
interface StoredAiPersonData extends AiPersonData {
  language: string;
  timestamp: number;
}

/**
 * 获取和管理AI角色数据的自定义Hook
 * 优先从localStorage获取，如果没有或过期则从API获取
 */
export const useAiPersonData = () => {
  // 从sessionStorage获取当前聊天的AI ID
  const getConversationId = (): string | null => {
    return sessionStorage.getItem('currentConversationId');
  };

  const [id, setId] = useState<string | null>(getConversationId());
  const { i18n } = useTranslation();
  const [aiPersonData, setAiPersonData] = useState<AiPersonData | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 语言代码转换函数
  const getLanguageCode = (lang: string): string => {
    if (lang.startsWith('zh')) return 'CN';
    if (lang.startsWith('ja')) return 'JP';
    return 'EN';
  };

  // 从localStorage获取数据
  const getStoredData = (personId: string, language: string): AiPersonData | null => {
    try {
      const storedDataStr = localStorage.getItem('AiPersioninfor');
      if (!storedDataStr) return null;

      const storedDataArray: StoredAiPersonData[] = JSON.parse(storedDataStr);
      const found = storedDataArray.find(
        item => item.id.toString() === personId && item.language === language
      );

      if (!found) return null;

      // 检查数据是否过期（24小时）
      const isExpired = Date.now() - found.timestamp > 24 * 60 * 60 * 1000;
      if (isExpired) return null;

      // 返回不包含language和timestamp的数据
      const { language: _, timestamp: __, ...personData } = found;
      return personData;
    } catch (error) {
      // console.error('读取localStorage数据失败:', error);
      console.error('read from localStorage failed',error);
      return null;
    }
  };

  // 保存数据到localStorage
  const saveToStorage = (personData: AiPersonData, language: string) => {
    try {
      const storedDataStr = localStorage.getItem('AiPersioninfor');
      let storedDataArray: StoredAiPersonData[] = [];

      if (storedDataStr) {
        storedDataArray = JSON.parse(storedDataStr);
      }

      // 移除相同id和语言的旧数据
      storedDataArray = storedDataArray.filter(
        item => !(item.id === personData.id && item.language === language)
      );

      // 添加新数据
      const newData: StoredAiPersonData = {
        ...personData,
        language,
        timestamp: Date.now()
      };
      storedDataArray.push(newData);

      // 只保留最近的10条数据，避免localStorage过大
      if (storedDataArray.length > 10) {
        storedDataArray = storedDataArray
          .sort((a, b) => b.timestamp - a.timestamp)
          .slice(0, 10);
      }

      localStorage.setItem('AiPersioninfor', JSON.stringify(storedDataArray));
    } catch (error) {
      // console.error('保存localStorage数据失败:', error);
      console.error('save to localStorage failed',error);
    }
  };

  // 从API获取数据
  const fetchFromAPI = async (personId: string, language: string): Promise<AiPersonData | null> => {
    try {
      const response = await request.post('/api/ai-persons/GetAiPersionDetail', {
        id: parseInt(personId),
        language
      });

      if (response.data.success && response.data.data) {
        const rawData = response.data.data;
        
        // 适应新的API数据结构，优先使用information对象中的数据
        const personData: AiPersonData = {
          id: rawData.id,
          image: rawData.avatar || '',
          avatar: rawData.avatar || '',
          // 优先使用information.name，回退到username
          username: rawData.information?.name || rawData.username || '',
          isPremium: rawData.is_premium || rawData.isPremium || false,
          description: rawData.description || '',
          images: rawData.images || [],
          videos: rawData.videos || [],
          // 保留原有字段作为回退，主要使用information中的数据
          age: rawData.information?.age || rawData.age || 0,
          gender: rawData.information?.gender || rawData.gender || '',
          zodiac: rawData.information?.zodiac || rawData.zodiac || '',
          birthday: rawData.information?.birthday || rawData.birthday || '',
          jobs: rawData.jobs || [],
          language: rawData.information?.language || rawData.language || '',
          occupation: rawData.information?.occupation || rawData.occupation || '',
          information: rawData.information,
          status: typeof rawData.status === 'boolean' ? rawData.status : undefined // 新增：在线状态
        };
        
        // 保存到localStorage
        saveToStorage(personData, language);
        return personData;
      } else {
        throw new Error(response.data.message ||'fetch for get PersionData failed');
      }
    } catch (error) {
      // console.error('API请求失败:', error);
      console.error('fetch from API failed',error);
      throw error;
    }
  };

  // 监听sessionStorage变化
  useEffect(() => {
    const handleStorageChange = () => {
      const newId = getConversationId();
      if (newId !== id) {
        setId(newId);
      }
    };

    // 监听storage事件（跨标签页的变化）
    window.addEventListener('storage', handleStorageChange);
    
    // 定期检查sessionStorage变化（同标签页内的变化）
    const interval = setInterval(handleStorageChange, 100);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      clearInterval(interval);
    };
  }, [id]);

  // 主要的数据获取逻辑
  useEffect(() => {
    const loadAiPersonData = async () => {
      if (!id) {
        setError('缺少角色ID参数');
        setLoading(false);
        return;
      }

      setLoading(true);
      setError(null);

      try {
        const currentLanguage = getLanguageCode(i18n.language);
        
        // 优先从localStorage获取
        const storedData = getStoredData(id, currentLanguage);
        if (storedData) {
          setAiPersonData(storedData);
          setLoading(false);
          return;
        }

        // localStorage中没有数据，从API获取
        const apiData = await fetchFromAPI(id, currentLanguage);
        if (apiData) {
          setAiPersonData(apiData);
        } else {
          setError('未找到AI角色数据');
        }
      } catch (error) {
        setError(error instanceof Error ? error.message : '获取数据失败');
      } finally {
        setLoading(false);
      }
    };

    loadAiPersonData();
  }, [id, i18n.language]);

  // 重新获取数据的函数
  const refetch = async () => {
    if (!id) return;

    setLoading(true);
    setError(null);

    try {
      const currentLanguage = getLanguageCode(i18n.language);
      const apiData = await fetchFromAPI(id, currentLanguage);
      if (apiData) {
        setAiPersonData(apiData);
      } else {
        setError('未找到AI角色数据');
      }
    } catch (error) {
      setError(error instanceof Error ? error.message : '获取数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 监听页面刷新事件，重新获取数据
  useEffect(() => {
    const handlePageRefreshReload = () => {
      // console.log('🤖 AiPersonData: 接收到页面刷新重载事件，重新获取数据');
      
      // 清除AI角色缓存数据
      localStorage.removeItem('AiPersioninfor');
      
      // 重置状态并重新获取数据
      setAiPersonData(null);
      refetch();
    };

    window.addEventListener('pageRefreshDataReload', handlePageRefreshReload);
    
    return () => {
      window.removeEventListener('pageRefreshDataReload', handlePageRefreshReload);
    };
  }, [refetch]);

  return {
    aiPersonData,
    loading,
    error,
    refetch
  };
}; 